package com.mobile.framework.action;

import com.mobile.framework.util.SpringContextUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.*;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * 应用中Struts Action类的基类，提供取Spring Bean实例的公共方法 以及log实例
 * 
 * Revision History
 */
public class BaseAction extends Action {

	protected Log log = LogFactory.getLog(getClass().getName());

	private ApplicationContext ctx = null;

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			Method method = this.getClass()
					.getDeclaredMethod(
							mapping.getPath().substring(1,
									mapping.getPath().length()),
							new Class[] { ActionMapping.class,
									ActionForm.class, HttpServletRequest.class,
									HttpServletResponse.class });
			return (ActionForward) method.invoke(this, new Object[] { mapping,
					form, request, response });
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	/*
	 * 初始化WebApplicationContext对象
	 * 
	 * @seeorg.apache.struts.action.Action#setServlet(org.apache.struts.action.
	 * ActionServlet)
	 */
	@Override
	public void setServlet(ActionServlet actionServlet) {
		super.setServlet(actionServlet);
		try {
			if (null == ctx) {
				ServletContext servletContext = actionServlet
						.getServletContext();
				long start = System.currentTimeMillis();
				ctx = WebApplicationContextUtils
						.getRequiredWebApplicationContext(servletContext);
				long end = System.currentTimeMillis();
				if (log.isDebugEnabled()) {
					log.debug("WebApplicationContext is inited ,spend: "
							+ (end - start) + " ms");
				}
			}
		} catch (Exception e) {
			log.error("setServlet error:" + e);
		}
		if (null == ctx) {
			// 非web容器环境,通过直接读取配置文件方式装载spring的 bean对象,主要用于测试用例代码运行
			ctx = SpringContextUtil.getApplicationContext();
		}
	}

	/**
	 * 获取Spring Bean实例
	 * 
	 * @param beanName
	 * @return Object
	 */
	protected Object getBean(String beanName) {
		return ctx.getBean(beanName);
	}

	/**
	 * 设置提示信息
	 * 
	 * @param request
	 * @param messageKey
	 */
	protected void setMessage(HttpServletRequest request, String messageKey) {

		ActionMessages messages = new ActionMessages();
		ActionMessage message = new ActionMessage(messageKey, false);
		messages.add(messageKey, message);
		saveMessages(request, messages);
	}

    protected void renderJSON(HttpServletResponse response, String result) throws IOException{
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter pw = response.getWriter();
        pw.write(result);
        pw.flush();
    }

    protected void renderText(HttpServletResponse response, String result) throws IOException{
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter pw = response.getWriter();
        pw.write(result);
        pw.flush();
    }
}